const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const token = 'treqrwetrewqqsd6543y5qwds'
const { koaBody } = require('koa-body');
const cookie = require('koa-cookie');


app.use(koaBody({ multipart: true }))
// app.use(cookie())


// 设置跨域访问
app.use(async (ctx, next) => {
    // 设置允许跨域的域名，*代表允许任意域名跨域
    ctx.set('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
    ctx.set('Access-Control-Allow-Methods', '*');
    ctx.set('Access-Control-Allow-Credentials', true);
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

    if (ctx.method === 'OPTIONS') {
        ctx.body = 200;
    } else {
        await next();
    }
})


// 登录接口
router.post('/login', (ctx) => {
    // 检验用户名和密码是否正确
    // 如果正确，返回登录成功 
    // 给前端设置登录凭证 cookie
    ctx.cookies.set('token', token, {
        expires: new Date(+new Date() + 1000 * 60 * 60 * 24 * 7),
        httpOnly: true,  // 是否只用于http请求中获取
        signed: false,  // 是否对 cookie进行签名
    })

    ctx.body = {
        code: 200,
        msg: '登录成功',
    }
})


app.use(async (ctx, next) => {
    if (ctx.url === '/login') {
        await next()
        return
    }
    const cookie = ctx.cookies.get('token')
    console.log(cookie);

})


// 首页接口
router.get('/home', (ctx) => {
    // 获取前端传递过来的token
    ctx.body = {
        code: 200,
        msg: '首页数据',
    }
})


app.use(router.routes());
app.listen(3000, () => {
    console.log('server is running at port 3000');
});